package Io.bio;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8081)) {
            System.out.println("BIO Server started on port 8081");
            int clientNumber = 1; // 用于区分不同的客户端线程
            while (true) {
                // 阻塞等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("New client connected: " + clientSocket.getInetAddress());
                
                // 为每个客户端创建一个新线程处理请求，并设置线程名称
                int finalClientNumber = clientNumber;
                Thread clientThread = new Thread(() -> {
                    Thread.currentThread().setName("ClientThread-" + finalClientNumber);
                    try (InputStream inputStream = clientSocket.getInputStream();
                         OutputStream outputStream = clientSocket.getOutputStream()) {
                        // 读取客户端数据（阻塞操作）
                        byte[] buffer = new byte[1024];
                        int bytesRead = inputStream.read(buffer);
                        if (bytesRead != -1) {
                            String request = new String(buffer, 0, bytesRead);
                            System.out.println("Received from client in thread " + Thread.currentThread().getName() + ": " + request);
                            
                            // 响应客户端
                            String response = "Server response to " + Thread.currentThread().getName() + ": " + request;
                            outputStream.write(response.getBytes());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
                clientThread.start();
                clientNumber++; // 增加客户端线程编号
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
